import java.util.*;

public class 三数之和 {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        int n = nums.length;
        Arrays.sort(nums);
        for (int i = 0;i < n - 2;) {
            int l = i + 1;
            int r = n - 1;
            int target = -nums[i];
            if (target < 0) {
                return ans;
            }
            while (l < r) {
                if (nums[l] + nums[r] > target) {
                    r--;
                } else if (nums[l] + nums[r] < target) {
                    l++;
                } else {
                    ans.add(List.of(nums[i],nums[l],nums[r]));
                    while (r - 1 >= 0 && nums[r] == nums[r - 1]) {
                        r--;
                    }
                    while (l + 1 < n && nums[l] == nums[l + 1]) {
                        l++;
                    }
                    l++;
                    r--;
                }
            }
            while (i + 1 < n && nums[i] == nums[i + 1]) {
                i++;
            }
            i++;
        }
        return ans;
    }
}
